package edu.hunau.annotation;

import edu.hunau.dao.UserDao;
import edu.hunau.dao.impl.UserDaoImpl;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

/**
 * @author hb
 * @date 2022-11-22 11:45:42
 */
public class MyApplicationContext {
    private Map<Class,Object> typeTypeMap=new HashMap<>();
    public MyApplicationContext(){
        UserDao userDao=new UserDaoImpl();
        //实例化对象
        typeTypeMap.put(UserDao.class,userDao);
    }
    public   Object context(String classPath){
        try {
            Class<?> clazz = Class.forName(classPath);
            //获得目标的实例对象
            Object target = clazz.getConstructor().newInstance();
            Field[] declaredFields = clazz.getDeclaredFields();
            for(Field field:declaredFields){
                if(field.isAnnotationPresent(MyAutoWired.class)){
                    field.setAccessible(true);
                    Class<?> type = field.getType();
                    Object o = typeTypeMap.get(type);
                    //为属性赋值
                    field.set(target,o);
                }
            }
            return target;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
